<template>
    <div style="padding: 20px">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/ques' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>问卷列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索筛选 -->
        <el-form :inline="true" :model="formInline" ref="formInline" class="paper-search" style="margin-top: 20px" :v-loading="loading">
            <el-form-item label="搜索：" prop="paperInfo">
                <el-input  size="small" v-model="formInline.paperInfo" placeholder="输入关键字"/>
            </el-form-item>
            <el-form-item prop="status">
                <el-select  size="small" v-model="formInline.status" placeholder="选择问卷状态">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="startTime">
                <el-date-picker
                        size="small"
                        v-model="formInline.startTime"
                        align="right"
                        type="date"
                        placeholder="选择开始日期"
                        :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item prop="endTime">
                <el-date-picker
                        size="small"
                        v-model="formInline.endTime"
                        align="right"
                        type="date"
                        placeholder="选择结束日期"
                        :picker-options="pickerOptions"
                        @change="changeDate()">
                </el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button size="small" @click="resetForm('formInline')">重置</el-button>
            </el-form-item>
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table
                v-loading="loading"
                :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                tooltip-effect="dark"
                stripe
                :cell-style="cellStyle"
                :header-cell-style="headerCellStyle">
            <el-table-column
                    type="index"
                    label="序号"
                    width="50px"
                    >
            </el-table-column>
            <el-table-column
                    prop="title"
                    label="问卷列表"
                    sortable
                    width="200px"
                    >
                <template slot-scope="scope">{{scope.row.title}}</template>
            </el-table-column>
            <el-table-column
                    prop="startTime"
                    label="开始日期"
                    sortable
                    width="120px"
                    show-overflow-tooltip>
            </el-table-column>
            <el-table-column
                    prop="endTime"
                    label="截止日期"
                    sortable
                    width="120px"
                    show-overflow-tooltip>
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="发布状态"
                    width="120px"
                    sortable>
                <template slot-scope="scope">
                    {{scope.row.status === '0' ? '未发布' : ''}}
                    {{scope.row.status === '1' ? '发布中':''}}
                    {{scope.row.status === '2' ? '已过期' : ''}}
                </template>
            </el-table-column>
            <el-table-column
                    prop="target"
                    label="参与对象"
                    sortable
                    show-overflow-tooltip>
                <template slot-scope="scope">
                    {{scope.row.target === '-#-#-' ? '-': scope.row.target == null ? '-' : scope.row.target}}
                </template>
            </el-table-column>
            <el-table-column
                    prop="completeFlag"
                    label="填写进度"
                    sortable
                    width="120px">
                <template slot-scope="scope">
                    {{scope.row.completeFlag === '1' ? '已完成':'未完成'}}
                </template>
            </el-table-column>
            <el-table-column
                    prop="handle"
                    label="操作"
                    show-overflow-tooltip>
                <template slot-scope="scope">
                    <!--查看问卷信息-->
                    <el-button
                            size="mini"
                            @click="writePaper(scope.row)">
                        点击进入
                    </el-button>
                    <!--下载问卷-->
                    <el-button type="primary"
                               size="mini"
                               @click="downLoadPaper(scope.row.paperId)">
                        下载问卷
                    </el-button>
                    <!--上传问卷-->
                    <el-button type="danger"
                               size="mini"
                               @click="dialogVisible2(scope.row)"
                               >
                        <!--@click="deletePaper(scope.row.paperId)"-->
                        上传问卷
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination
                style="float: right;margin-right: 30px;margin-top: 20px"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5, 10, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.length">
        </el-pagination>

        <el-dialog
                :title="title2"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
            <el-upload drag
                       ref="my-upload"
                       :limit=limitNum
                       :auto-upload="false"
                       accept=".xls,.xlsx"
                       :action="UploadUrl()"
                       :before-upload="beforeUploadFile"
                       :on-change="fileChange"
                       :on-exceed="exceedFile"
                       :on-success="handleSuccess"
                       :on-error="handleError"
                       :file-list="fileList">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件，且不超过10M</div>
            </el-upload>
            <span slot="footer" class="dialog-footer" style="margin-right: 10px">
                <el-button size="small" type="primary" @click="uploadFile()">立即上传</el-button>
            </span>
            <el-button @click="clearFiles">重新上传</el-button>
        </el-dialog>
    </div>
</template>

<script>
    import {getPaperDetail, paperListsByUser} from "../../../api/paperMG";
    import {getExcelPath, validExcel} from "../../../api/resourceMG";

    export default {
        name: "write-ques",
        data() {
            return {
                loading: true,
                value1: true,
                tableData: [],
                excelPath: '',
                multipleSelection: [],
                //单选框-问卷状态
                options: [{
                    value: '0',
                    label: '未发布问卷'
                }, {
                    value: '1',
                    label: '已发布问卷'
                },{
                    value: '2',
                    label: '往期问卷'
                }],
                //搜索问卷信息对象
                formInline: {
                    paperInfo: '',
                    status: '',
                    startTime: '',
                    endTime: ''
                },

                //选择日期
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },
                //分页
                currentPage:1, //初始页
                pageSize:10,    //每页的数据

                dialogVisible: false, //弹出框

                visible: false,
                type: '',
                limitNum: 1,  // 上传excell时，同时允许上传的最大数
                fileList: [],   // excel文件列表
                title2:''
            }
        },
        methods:{
            //表格单元格样式设计 --wzr 20210418
            headerCellStyle() {
                return "text-align: center;";
            },
            cellStyle({row, column, rowIndex, columnIndex}) {//根据测试结果动态调整单元格样式，成功-绿色，失败-红色，不支持-黄色
                return "text-align: center;";
                let cellStyle;
                //指定列
                if (columnIndex === 5) {

                }
                switch (row.testResult) {
                    case '成功':
                        cellStyle = 'background: green;color:white';
                        break;
                    case '失败':
                        cellStyle = 'background: red;color:white';
                        break;
                    case '不支持':
                        cellStyle = 'background: #aaa;color:white';
                        break;
                    default:
                        cellStyle = '';
                }
                if (column.label === '测试结果')
                    return cellStyle;
            },

            //初始化问卷列表
            async getQuesList() {
                let token = localStorage.getItem('JWT_TOKEN');
                console.log("======token=====",token)
                paperListsByUser(token).then(res => {
                    if (res.code === 200) {
                        this.tableData = res.data;
                        this.loading = false;
                        console.log("res.data===========",res.data);
                        console.log("res.data===========",res.data.completeFlag);


                        return ;
                    }
                    this.loading = false;
                    return this.$message('获取用户列表失败！')
                });
            },

            // 初始页currentPage、初始每页数据数pageSize和数据data
            handleSizeChange: function (size) {
                this.pageSize = size;
                console.log(this.pageSize)  //每页下拉显示数据
            },
            handleCurrentChange: function(currentPage){
                this.currentPage = currentPage;
                console.log(this.currentPage)  //点击第几页
            },

            //进入问卷
            writePaper(paperInfo) {
                let token = localStorage.getItem("JWT_TOKEN");
                let paperInfor = {
                    token : token,
                    paperId : paperInfo.paperId,
                };
                getPaperDetail(paperInfor).then(res=>{
                    console.log("问卷数据=====>",res);
                    let data = {

                    };
                    this.$router.push({name:"WriteSave",params:res.data})
                });
            },

            //下载模板
            downLoadPaper(paperId) {
                getExcelPath(paperId).then(res=>{
                   console.log("得到路径===>",res.data);
                   this.excelPath = res.data;
                    console.log("=========下载开始==========");
                    window.open("localhost:8082\\" + this.excelPath+"?"+Math.random());
                });

            },

            //组件方法
            init(params) {
                this.visible = true;
                this.type = params
            },
            // 文件超出个数限制时的钩子
            exceedFile(files, fileList) {
                this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`);
            },
            // 文件状态改变时的钩子
            fileChange(file, fileList) {
                console.log("======fileChange======");
                console.log(file.raw);
                this.fileList.push(file.raw);
                console.log(this.fileList);
            },
            // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
            beforeUploadFile(file) {
                console.log('=======before upload=======');
                console.log(file);
                let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
                let size = file.size / 1024 / 1024;
                if (extension !== 'xlsx' || extension !== 'xls') {
                    this.$message.warning('只能上传后缀是.xls/.xlsx的文件');
                }
                if (size > 10) {
                    this.$message.warning('文件大小不得超过10M');
                }
            },
            // 文件上传成功时的钩子
            handleSuccess(res, file, fileList) {
                this.$message.success('文件上传成功');
            },
            // 文件上传失败时的钩子
            handleError(err, file, fileList) {
                this.$message.error('文件上传失败');
            },
            UploadUrl: function () {
                // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
                return ""
            },
            uploadFile() {

                if (this.fileList.length === 0) {
                    this.$message.warning('请上传文件');
                } else {
                    //使用formdata格式传照片
                    let form = new FormData();
                    form.append('file', this.fileList[0]);
                    console.log("data-form=====>",form);
                    this.$axios({
                        method: "post",
                        url: "/api/v1/excel/upload",
                        headers: {
                            Authorization : localStorage.getItem('JWT_TOKEN'),
                            'Content-type': 'multipart/form-data'
                        },
                        data: form
                    }).then(res => {
                            if (res.data.code === 200) {
                                let token = window.localStorage.JWT_TOKEN;
                                let paperId = window.localStorage.PAPERID;
                                let title = window.localStorage.TITLE;
                                console.log("info==========>paperId",paperId);
                                console.log("info==========>title",title);
                                console.log("info==========>token",token);
                                validExcel(paperId,title,token).then(res=>{
                                    console.log("res===>",res)
                                    if (res.code === 200) {
                                        this.$message({
                                            message: '解析成功',
                                            type: 'success'
                                        });
                                        this.dialogVisible = false;
                                        this.getQuesList();
                                    }
                                });
                            }
                            this.visible = false
                        }, err => {
                        });
                }
            },
            handleClose(done) {
                this.$confirm('取消上传，继续？')
                    .then(() => {
                        this.clearFiles();
                        done();
                    })
                    .catch(() => {
                    });
            },
            dialogVisible2(paperInfo){
                window.localStorage.PAPERID = paperInfo.paperId;
                window.localStorage.TITLE = paperInfo.title;
                console.log("window.localStorage.PAPERID",window.localStorage.PAPERID);
                console.log("window.localStorage.TITLE",window.localStorage.TITLE);
                this.title2 = "请上传["+paperInfo.title+"]问卷对应的Excel";
                this.dialogVisible = true;
            },
            clearFiles(){
                this.$refs['my-upload'].clearFiles();
                this.fileList = [];
            }
        },
        created() {
            this.getQuesList();
        },
    }
</script>

<style scoped>

</style>